import { Scene } from "phaser"

import { EVENTS_NAME, GameStatus } from "../consts"
import { Actor } from "./actor"
import { Text } from "./text"

export class Player extends Actor {
  private cursors: Phaser.Types.Input.Keyboard.CursorKeys | any;
  private hpValue: Text

  constructor(scene: Scene, x: number, y: number) {
    super(scene, x, y, "king");

    this.cursors = this.scene?.input?.keyboard?.createCursorKeys();//获得键盘方向键

    // scene.add.existing(this);
    // scene.physics.add.existing(this);

    //文本显示：角色头部上方显示一个HP值
    this.hpValue = new Text(
      this.scene,
      this.x,
      this.y - this.height,
      this.hp?.toString()
    )
      .setFontSize(12)
      .setOrigin(0.8, 0.5)

    //PHYSICS
    this.getBody().setSize(30, 30);
    this.getBody().setOffset(8, 8);

    //ANIMATIONS
    this.initAnimations()
  }

  update(): void {
    this.getBody().setVelocity(0) //设置物体的速度为0，可以停止物体的移动

    if (this.cursors.up.isDown) {
      this.getBody().velocity.y = -110
      !this.anims.isPlaying && this.anims.play('run', true) //待方向键按下就调用动画
    }

    if (this.cursors.left.isDown) {
      this.getBody().velocity.x = -110
      this.checkFlip()
      this.getBody().setOffset(48, 15)//左边临界点
      !this.anims.isPlaying && this.anims.play('run', true)
    }

    if (this.cursors.down.isDown) {
      this.getBody().velocity.y = 110
      !this.anims.isPlaying && this.anims.play('run', true)
    }

    if (this.cursors.right.isDown) {
      this.getBody().velocity.x = 110
      this.checkFlip()
      this.getBody().setOffset(15, 15)
      !this.anims.isPlaying && this.anims.play('run', true)
    }

    if (this.cursors.space.isDown) {
      //检测空格键是否按下, 播放Player的攻击动画，并且发送一个全局事件
      this.anims.play('attack', true)
      this.scene.game.events.emit(EVENTS_NAME.attack)
    }

    //HP值文本显示
    this.hpValue.setPosition(this.x, this.y - this.height * 0.4)
    this.hpValue.setOrigin(0.8,0.5)
  }

  // 初始动画设置
  // 跑步动画
  private initAnimations(): void {
    this.scene.anims.create({
      key: 'run',
      frames: this.scene.anims.generateFrameNames('a-king', {
        prefix: 'run-',
        end: 7
      }),
      frameRate: 8,
    })

    //攻击动画
    this.scene.anims.create({ //在场景中创建一个新的动画
      key: 'attack', // 动画的唯一key(标识符)
      frames: this.scene.anims.generateFrameNames('a-king', {//生成动画帧名称
        prefix: 'attack-', // 帧名称的前缀
        end: 2 // 帧的结束编号
      }),
      frameRate: 8, // 每秒播放的帧数
    })
  }

  public addHP() {
    this.hp = this.hp + 10
    this.hpValue.setText(this.hp.toString())
  }

  //收到伤害逻辑，更新文案分数-HP 值将显示在游戏角色的上方，在 update 方法中，我们更新了 HP 文本值的位置，这样即使 PLayer 移动也不会有问题。
  public getDamage(value?: number): void {
    console.log('z-攻击怪物收到伤害事件');

    super.getDamage(value) //递归
    this.hpValue.setText(this.hp?.toString())

    if(this.hp <= 0) {
      this.scene.game.events.emit(EVENTS_NAME.gameEnd, GameStatus.LOSE)
    }
  }
}
